package com.piggy.sys.service.base.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.piggy.sys.api.vo.BaseAddressVo;
import com.piggy.sys.domain.base.BaseCity;
import com.piggy.sys.domain.base.BaseProvince;
import com.piggy.sys.domain.vo.CityAddressVo;
import com.piggy.sys.mapper.base.BaseCityMapper;
import com.piggy.sys.mapper.base.BaseProvinceMapper;
import com.piggy.sys.service.base.IBaseCityService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 市
 */
@Service
public class BaseCityServiceImpl extends ServiceImpl<BaseCityMapper, BaseCity> implements IBaseCityService {

    @Resource
    private BaseProvinceMapper baseProvinceMapper;

    @Override
    public List<BaseAddressVo> getCity(String parentId) {
        List<BaseCity> baseCityList = baseMapper.selectList(Wrappers.<BaseCity>lambdaQuery().eq(BaseCity::getPid, parentId));
        return BeanUtil.copyToList(baseCityList, BaseAddressVo.class);
    }

    @Override
    public List<CityAddressVo> getAllCityInfo() {
        List<BaseProvince> baseProvinceList = baseProvinceMapper.selectList(Wrappers.<BaseProvince>lambdaQuery());
        List<BaseCity> baseCityList = baseMapper.selectList(Wrappers.<BaseCity>lambdaQuery());
        Map<String, List<BaseCity>> baseCityMap = baseCityList.stream().collect(Collectors.groupingBy(BaseCity::getPid));

        List<CityAddressVo> cityAddressVoList = Lists.newArrayList();
        for (BaseProvince baseProvince : baseProvinceList) {
            List<BaseCity> cityList = baseCityMap.get(baseProvince.getId().toString());
            if (CollUtil.isEmpty(cityList)) {
                continue;
            }
            cityList.forEach(baseCity -> {
                CityAddressVo addressVo = new CityAddressVo();
                addressVo.setProvinceId(baseProvince.getId().toString());
                addressVo.setCityId(baseCity.getId().toString());
                addressVo.setAddressName(baseProvince.getName() + baseCity.getName());
                cityAddressVoList.add(addressVo);
            });
        }
        return cityAddressVoList;
    }
}
